package com.zly.jwt.filter;

import com.zly.jwt.properties.JwtProperties;
import com.zly.jwt.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

@Component
public class JwtFilter extends OncePerRequestFilter {
    private final String HEADER_NAME = "Authorization";
    @Resource
    private JwtProperties jwtProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(HEADER_NAME);
        if (StringUtils.hasText(token)) {
            Claims claims = new JwtUtils().parseToken(token, jwtProperties.getSecretKey());
            Object principal = claims.get("principal");
            ArrayList<String> authorities = claims.get("authority", ArrayList.class);
            Collection<SimpleGrantedAuthority>  simpleGrantedAuthorities= new ArrayList<>();
            for (String authority : authorities) {
                simpleGrantedAuthorities.add(  new SimpleGrantedAuthority(authority));
            }
            Object credential = claims.get("credential");
            UsernamePasswordAuthenticationToken authenticated = UsernamePasswordAuthenticationToken.authenticated(principal, credential, simpleGrantedAuthorities);
            SecurityContextHolder.getContext().setAuthentication(authenticated);
            filterChain.doFilter(request, response);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
